package com.ubing.boot.notesforjava.test.juc;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName : MyContainer2
 * @Description : MyContainer2
 * @Author : Xxxxx
 * @Date: 2023-03-14 14:18
 */
public class MyContainer2<T> {
    final private LinkedList<T> lists =  new LinkedList();
    final private int MAX =10;
    private int count=0;

    private Lock lock=new ReentrantLock();
    private Condition producer=lock.newCondition();
    private Condition consumer=lock.newCondition();
    public void put(T t){
        try {
            lock.lock();
            while (count==MAX){
                producer.await();// 悲观
            }
            lists.add(t);
            ++count;
            consumer.signalAll();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public T get(){
        T t=null;
        lock.lock();
        try {
            while (count==0){
                consumer.await();
            }
            t = lists.removeFirst();
            count--;
            producer.signalAll();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return t;
    }

    public static void main(String[] args) {
        MyContainer2<String> container=new MyContainer2<>();
        // 启动消费者线程
        for (int i = 0; i <10 ; i++) {
            new Thread(()->{
                for (int j = 0; j <5 ; j++) {
                    System.out.println(Thread.currentThread().getName()+"=="+container.get());
                }
            },"c"+i).start();
        }
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 启动生产者线程
        for (int i = 0; i <2 ; i++) {
            new Thread(()->{
                for (int j = 0; j < 25; j++) {
                    container.put(Thread.currentThread().getName()+"--"+j);
                }
            },"p"+i).start();
        }

    }
}
